/**
 * Created by Administrator on 2017/7/24.
 */

var hiddenMaterial = new Object();
var page;
var company_name;

    // 初始化
hiddenMaterial.init = function(page){
        page=page;
        this.tree();
        this.initListTable(page);
 };

hiddenMaterial.initListTable= function(){
    var list_url = appPath+"/admin/hiddenMaterial/queryList";

    /*
     * 分页
     * @param param_form 参数form id
     * @param list_url 请求链接
     * @param tbody_id 列表div id
     * @param page_id 分页id
     * @param pageNum 页数
     * @param pageSize 每页条数
     */
    page.init("hiddenMaterialListForm", list_url, "hidden_material_tbody", "hidden_material_page", 1, 10);

    //初始化
    page.goPage(1);

    //重写组装方法
    page.list = function(dataList){
        var len = dataList.length;
        var inner = "", item, businessName;
        for(var i=0; i< len; i++) {
            item = dataList[i];
            businessName = item.businessName;
            if(businessName && businessName.length > 9){
                businessName = businessName.substr(0,7) + '..';
            }
            // 组装数据
            inner += "<tr>";
            inner += "<td width='40'>"+(parseInt(i)+1)+"</td>";
            inner += "<td width='40' ><input type='checkbox'name='check' value='"+item.id+"'/></td>";
            inner += "<td width='80'>"+item.sourceNo+"</td>";
            inner += "<td width='120' title='"+item.businessName+"'>"+businessName+"</td>";
            inner += "<td width='80'>"+item.sourceNum+"</td>";
            inner += "<td width='60'>"+item.createUser+"</td>";
            inner += "<td width='100'>"+item.operTime.substring(0,10)+"</td>";
            inner += "<td width='300'><a href=javascript:manager('"+item.id+"') class='a a-view'>隐患管理</a>&nbsp;";
            inner += "<a href=javascript:view('"+item.id+"') class='a a-publish'>预览</a>&nbsp;";
            inner += "<a href=javascript:hiddenMaterial.update('"+item.id+"') class='a a-info'>编辑</a>&nbsp;";
            inner += "<a href=javascript:hiddenMaterial.delete('"+item.id+"') class='a a-close'>删除</a>&nbsp;";
            inner += "</td>";
            inner += "</tr>";
        }
        return inner;
    }

};

    //模糊查询
    hiddenMaterial.search=function (){
        this.initListTable();
    };

    //查询全部
    hiddenMaterial.searchAll=function(){
        $("#sourceNo").val("");
        this.initListTable();
    };

    var zTree;
    var strId=''; //选中部门的节点
    var rMenu = $("#rMenu");
    // tree options
    var tree_options = {
        id: 'material_type_tree',
        url: appPath + '/admin/materialType/tree',
        setting: {
            /*check: {
                enable: true,
                chkStyle: "radio"
            },*/
            data: {
                simpleData: {
                    enable: true
                }
            },

            view: {
                dblClickExpand: false,
                fontCss: getFontCss
            },
            callback: {
                onRightClick: function(event, treeId, treeNode){
                    var id = treeNode.id.toString();
                    if(id.indexOf("yourself_") != -1){
                        return;
                    }
                   onRightClick(event, treeId, treeNode);
                },
                onClick: function(e,treeId, treeNode){
                    // 获取左侧选中节点
                    var companyId = (treeNode.companyId)?treeNode.companyId:"";
                    var materialTypeId = (treeNode.materialTypeId)?treeNode.materialTypeId:"";
                    var materialTypeName = (treeNode.name)?treeNode.name:"";
                    var id = treeNode.id.toString();

                    $("#materialTypeId").attr("value",materialTypeId);
                    $("#materialTypeName").attr("value",materialTypeName);
                    $("#companyId").attr("value",companyId);
                    hiddenMaterial.initListTable();
                },
                onRename: function(event, treeId, treeNode, isCancel){
                    this.zTreeOnRename(event, treeId, treeNode, isCancel);
                }
              /*  onCheck: function(e,treeId, treeNode){
                    onCheck(e,treeId, treeNode);
                }*/
            }
        },
        zNodes : '',
        rMenu : ''
    };

    //搜索高亮
    function getFontCss(treeId, treeNode){
        return (!!treeNode.highlight)?{'color': "#A60000", 'font-weight':"bold"}:{'color': "#333", 'font-weight':"normal"};
    }




    hiddenMaterial.getRole = function(){
        var treeObj = $.fn.zTree.getZTreeObj(tree_options.id);
        var rootNode = this.getRoots()[0];
        treeObj.selectNode(rootNode);
        treeObj.setting.callback.onClick(null, tree_options.id, rootNode);
    };
    hiddenMaterial.zTree = null;
    hiddenMaterial.rMenu = null;
    // 初始化树
    hiddenMaterial.tree = function(){
        $.ajax({
            url: tree_options.url,
            async: false,
            type: 'post',
            data: {

            },
            success: function(data){
                var zNodes = JSON.parse(data.result);
                if(zNodes && zNodes.length>0){
                    var objDate = zNodes[0];
                    company_name = objDate.name ;
                }
                // 加载树
                $.fn.zTree.init($("#"+tree_options.id), tree_options.setting, zNodes);
                // 根节点下添加退厂节点
                // hiddenMaterial.zTree = $.fn.zTree.getZTreeObj(tree_options.id);
                // var rootNode =getRoots()[0];

                //本公司
                //离职
                // hiddenMaterial.addDefaultNode(rootNode, null, 'quit', rootNode.id, '离职人员', rootNode.id, "-1", false);

                setTimeout(function(){
                }, 200);
                // hiddenMaterial.zTree.expandAll(true);
            }
        });
    };

    //新增素材
    hiddenMaterial.add = function () {
        // 获取素材类型id
        var selectedNodes = $.fn.zTree.getZTreeObj(tree_options.id).getSelectedNodes();
        if (selectedNodes.length == 0) {
            layer.alert('请选择节点', {icon: 2, skin: 'layer-ext-moon'});
            return;
        }
        var selectedNode = selectedNodes[0];
        var typeId = selectedNode.id;
        if(typeId == '0'){
            layer.alert('请选择非根节点', {icon: 2, skin: 'layer-ext-moon'});
            return;
        }
        layer.open({
            type: 2,
            title: '新增隐患素材',
            area: ['900px', '750px'],		//弹出层大小
            scrollbar: false,				//false隐藏滑动块
            content: [appPath + '/admin/hiddenMaterial/add?typeId=' + typeId, 'yes']
        });
    };

    //修改素材
    hiddenMaterial.update = function (id) {
        layer.open({
            type: 2,
            title: '修改隐患素材',
            area: ['900px', '750px'],		//弹出层大小
            scrollbar: false,				//false隐藏滑动块
            content: [appPath + '/admin/hiddenMaterial/update?id=' + id, 'yes']
        });
    };

    hiddenMaterial.addDefaultNode = function (rootNode, index, id, pid,name,companyId,materialTypeId,doCheck) {
        var treeNode = new Object();
        treeNode.id = id;
        treeNode.pid = pid;
        treeNode.name = name;
        treeNode.companyId = companyId;
        treeNode.materialTypeId = materialTypeId;
        treeNode.doCheck = doCheck;
        if(null != index){
            hiddenMaterial.zTree.addNodes(rootNode, index, treeNode, false);
            return;
        }
        hiddenMaterial.zTree.addNodes(rootNode, treeNode, false);
    };

      //删除节点
    hiddenMaterial.removeTreeNode = function(e){
        hideRMenu();
        var selectedNodes = $.fn.zTree.getZTreeObj(tree_options.id).getSelectedNodes();
        if(selectedNodes.length==0){
            layer.alert('请选择节点', {icon: 2,  skin: 'layer-ext-moon'});
            return;
        }
        var selectedNode = selectedNodes[0];
        var params = {
            'companyId': selectedNode.companyId,
            'materialTypeId': selectedNode.materialTypeId
        };
        if (selectedNode.children && selectedNode.children.length > 0) {
            layer.confirm('提示：您要删除的节点包含子节点，如果删除将连同子节点,及其素材一起删掉', {
                btn: ['删除','取消'] //按钮
            }, function(){
                hiddenMaterial.remove(params);
            }, function(){
                // 取消删除
            });
        }else{
            layer.confirm('确定删除该节点吗？', {
                btn: ['删除','取消'] //按钮
            }, function(){
                hiddenMaterial.remove(params);
            });
        }
    };

    // 删除节点
    hiddenMaterial.remove = function(params){
        $.ajax({
            url: appPath + '/admin/materialType/delMaterialType',
            async: false,
            type: 'post',
            data: params,
            success: function(data){
                var result = data['result'];
                var message;
                if(result){
                    layer.alert('操作成功', {icon: 1,  skin: 'layer-ext-moon'}, function(index){
                        layer.close(index);
                        // 刷新树
                        hiddenMaterial.tree();
                    });
                }else{
                    layer.alert((data['message'])?data['message']:'操作失敗', {icon: 2,  skin: 'layer-ext-moon'});
                    // layer.alert("操作失敗,该隐患类别下存在素材不能删除", {icon: 2,  skin: 'layer-ext-moon'});
                }
            }
        });
      };

    //修改名称
    hiddenMaterial.renameTreeNode = function(e){
        hideRMenu();
        var selectedNodes = $.fn.zTree.getZTreeObj(tree_options.id).getSelectedNodes();
        if(selectedNodes.length==0){
            layer.alert('请选择节点', {icon: 2,  skin: 'layer-ext-moon'});
            return;
        }
        var selectedNode = selectedNodes[0];
        var node='';
        if (selectedNodes.length > 0) {
             node = selectedNodes[0].getParentNode();
        }
        // 请输入节点名称
        var promptIndex = layer.prompt({
            title : '输入新的节点名称，并确认',
            formType : 2,
            maxlength:40,
            value: selectedNode.name
        }, function(text) {
            layer.close(promptIndex);
            var selectedNode = selectedNodes[0];
            var params = {
                'companyId': selectedNode.companyId,
                'materialTypeId': selectedNode.materialTypeId,
                'materialTypeName': $.trim(text),
                // 'materialTypeNames': node.pId == null?'':node.name
            };
            if(checkName($.trim(text))){
                layer.msg("隐患素材类别已存在");
                return;
            }
            $.ajax({
                url: appPath + '/admin/materialType/updateMaterailTypeNment',
                async: false,
                type: 'post',
                data: params,
                success: function(data){
                    var result = data['result'];
                    var message;
                    if(result){
                        layer.alert('操作成功', {icon: 1,  skin: 'layer-ext-moon'}, function(index){
                            layer.close(index);

                            // 获取左侧选中节点
                            var companyId = (selectedNode.companyId)?selectedNode.companyId:"";
                            var materialTypeId = (selectedNode.materialTypeId)?selectedNode.materialTypeId:"";
                            $("#materialTypeId").attr("value",materialTypeId);
                            $("#companyId").attr("value",companyId);
                            hiddenMaterial.initListTable();
                            // 刷新树
                           hiddenMaterial.tree();
                            //alert(value)
                            //selectedNode.name = value;
                            //selectedNode.checked = true;
                            //$.fn.zTree.getZTreeObj(tree_options.id).updateNode(selectedNode);
                        });
                    }else{
                        layer.alert((data['message'])?data['message']:'操作失敗', {icon: 2,  skin: 'layer-ext-moon'});
                    }
                }
            });
        });
    };

    //添加节点(0:平级节点；1：子级节点)
    hiddenMaterial.addTreeNode = function(ntp){
        hideRMenu();
        var selectedNodes = $.fn.zTree.getZTreeObj(tree_options.id).getSelectedNodes();
        if(selectedNodes.length==0){
            layer.alert('请选择节点', {icon: 2,  skin: 'layer-ext-moon'});
            return;
        }
        var selectedNode = selectedNodes[0];
        // 请输入节点名称
        var promptIndex = layer.prompt({
            title : '输入要添加的节点名称，并确认',
            formType : 2,
            maxlength:40
        }, function(text) {
            var params = {
                'materialTypeId': selectedNode.materialTypeId,
                'materialTypeName': $.trim(text),
                'ifChild': ntp
            };
            if(text.length>40){
                layer.msg("隐患类别名称超出长度限制");
                return;
            }
            if(checkName($.trim(text))){
                layer.msg("隐患类别名称已存在");
                return;
            }
            $.ajax({
                url: appPath + '/admin/materialType/addMaterialType',
                async: false,
                type: 'post',
                data: params,
                success: function(data){
                    var result = data['result'];
                    var message;
                    if(result){
                        layer.alert('操作成功', {icon: 1,  skin: 'layer-ext-moon'}, function(index){
                            layer.close(index);
                            layer.close(promptIndex);
                            // 刷新树
                            hiddenMaterial.tree();
                        });
                    }else{
                        layer.alert((data['message'])?data['message']:'操作失敗', {icon: 2,  skin: 'layer-ext-moon'});
                    }
                }
            });
        });
    };

    function checkName(materialTypeName){
    var flag = false;
    $.ajax({
        url: appPath + '/admin/materialType/checkMaterialTypeName',
        async: false,
        type: 'post',
        data: {
            'materialTypeName':materialTypeName
        },
        success: function(data){
            var result = data['result'];
            flag = result;
        }
    });
    return flag;
    }

    function onRightClick(event, treeId, treeNode) {
        var scrollTop = $(window).scrollTop();
        var pageX = event.clientX;
        var pageY = event.clientY + scrollTop;
        zTree = $.fn.zTree.getZTreeObj(tree_options.id);
        zTree.selectNode(treeNode);
        showRMenu(pageX ,pageY , treeNode);
     }

    function showRMenu(x, y,treeNode) {
          if("-1"==treeNode.materialTypeId){
            if("quit"==treeNode.id){
                // 退厂节点
                $("#m_add").hide();
                $("#m_p_add").hide();
                $("#m_del").hide();
                $("#m_reset").hide();
                $("#m_moveup").hide();
                $("#m_movedown").hide();
            }
          }else if(""==treeNode.materialTypeId){//根节点
              $("#m_add").show();
              $("#m_p_add").hide();
              $("#m_del").hide();
              $("#m_reset").hide();
              $("#m_moveup").hide();
              $("#m_movedown").hide();
          }else{
            // 部门节点
            $("#m_add").show();
            $("#m_p_add").show();
            $("#m_del").show();
            $("#m_reset").show();
            $("#m_moveup").show();
            $("#m_movedown").show();
        }
        $("#rMenu").css({"top":y+"px", "left":x+"px", "visibility":"visible"});

        $("body").bind("mousedown", onBodyMouseDown);
    }

    function onBodyMouseDown(event){
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
            rMenu.css({"visibility" : "hidden"});
        }
    }

    function hideRMenu() {
        if (rMenu) rMenu.css({"visibility": "hidden"});
        $("body").unbind("mousedown", onBodyMouseDown);
    }

    //全选与非全选
    $("#checkAll").click(function(){
        if(this.checked){
            $("#hidden_material_tbody :checkbox").prop("checked", true);
        }else{
            $("#hidden_material_tbody :checkbox").prop("checked", false);
        }
    });

   //修改
    function modifyPassWord(userId){
        location.href=appPath + '/admin/user/userModify?id='+userId;
    }

    // 上移
    hiddenMaterial.moveUp = function(){
        var selectedNodes = $.fn.zTree.getZTreeObj(tree_options.id).getSelectedNodes();
        if(selectedNodes.length==0){
            layer.alert('请选择节点', {icon: 2,  skin: 'layer-ext-moon'});
            return;
        }
        var selectedNode = selectedNodes[0];
        var params = {
            'companyId': selectedNode.companyId,
            'materialTypeId': selectedNode.materialTypeId
        };
        $.ajax({
            url: appPath + '/admin/materialType/moveUp',
            async: false,
            type: 'post',
            data: params,
            success: function(data){
                var result = data['result'];
                var message;
                if(result){
                    layer.alert('操作成功', {icon: 1,  skin: 'layer-ext-moon'}, function(index){
                        layer.close(index);
                        // 刷新树
                        hiddenMaterial.tree();
                    });
                }else{
                    layer.alert((data['message'])?data['message']:'操作失敗', {icon: 2,  skin: 'layer-ext-moon'});
                }
            }
        });
    };

    // 下移
    hiddenMaterial.moveDown = function(){
        var selectedNodes = $.fn.zTree.getZTreeObj(tree_options.id).getSelectedNodes();
        if(selectedNodes.length==0){
            layer.alert('请选择节点', {icon: 2,  skin: 'layer-ext-moon'});
            return;
        }
        var selectedNode = selectedNodes[0];
        var params = {
            'companyId': selectedNode.companyId,
            'materialTypeId': selectedNode.materialTypeId
        };
        $.ajax({
            url: appPath + '/admin/materialType/moveDown',
            async: false,
            type: 'post',
            data: params,
            success: function(data){
                var result = data['result'];
                var message;
                if(result){
                    layer.alert('操作成功', {icon: 1,  skin: 'layer-ext-moon'}, function(index){
                        layer.close(index);
                        // 刷新树
                        hiddenMaterial.tree();
                    });
                }else{
                    layer.alert((data['message'])?data['message']:'操作失敗', {icon: 2,  skin: 'layer-ext-moon'});
                }
            }
        });
    };

    /**
     * 删除
     */
    hiddenMaterial.delete = function (ids){
        layer.confirm("确定删除吗?", {
            icon : 3,
            btn : [ "确认", "取消" ]
        }, function() {
            $.ajax({
                url: appPath + '/admin/hiddenMaterial/delete',
                async: false,
                type: 'post',
                data: {
                    'ids': ids	// 人员id
                },
                success: function (data) {
                    var code = data['code'];
                    if (code == '10000') {
                       layer.msg('删除成功');
                       parent.hiddenMaterial.initListTable();
                    } else {
                        layer.alert((data['message']) ? data['message'] : '删除失敗', {icon: 2, skin: 'layer-ext-moon'});
                    }
                }
            });
        })
    }

    /**
     * 批量删除
     */
    hiddenMaterial.batchDelete=function(){
        // 获取选择人员
        var array = new Array;
        var pkidObj = document.getElementsByName("check");
        for ( var j = 0; j < pkidObj.length; j++) {
            if (pkidObj.item(j).checked == true) {
                array.push(pkidObj.item(j).value);
            }
        }
        if(array.length==0){
            layer.msg("未勾选人员");
            return;
        }
        hiddenMaterial.delete(array.join(","));
    };

    function manager(id) {
        layer.open({
            type: 2,
            title: '隐患管理',
            area: ['900px', '750px'],		//弹出层大小
            scrollbar: false,				//false隐藏滑动块
            content: [appPath + '/admin/hiddenMaterial/hidden?id=' + id , 'yes']
        });
    }

    function view(id) {
        layer.open({
            type: 2,
            title: '预览',
            area: ['900px', '750px'],		//弹出层大小
            scrollbar: false,				//false隐藏滑动块
            content: [appPath + '/admin/hiddenMaterial/view?id=' + id , 'yes']
        });
    }